/**
 * Created by zhouli on 18/2/7
 * Email li.zhou@huilianyi.com
 * 关于人员导出的一些函数，对应的服务注释掉了
 * 统一用导出组件 export-modal
 */
import React from 'react';
import {
  Button, Tag, Popover, message,
  Icon, Menu, Dropdown, Modal, Upload
} from 'antd';
import {connect} from 'react-redux';
import PMService from 'containers/enterprise-manage/person-manage/person-manage.service';
import SearchArea from 'components/search-area.js';
import menuRoute from 'routes/menuRoute';
import 'styles/enterprise-manage/person-manage/person-manage.scss';
import {isEmptyObj, messages} from 'share/common';
import antdc from 'share/prototype-extend/antd-common';
import {deepCopy} from 'share/common';
import {SelectDepOrPerson} from 'components/index';
import InvitePersonModal from 'containers/enterprise-manage/person-manage/person-manage-components/invite.person.modal'
import ExportModal from 'components/template/export-modal/export-modal';
import debounce from 'lodash.debounce';
import {employeeStatusList, exportList} from 'containers/enterprise-manage/person-manage/person-manage.model'
import ImportModal from "components/template/import-modal-ie/import-modal";
import config from "config";
import ResizeTable from 'components/resize-table'

class PersonManage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cacheObj: {
        "keyword": "",//关键字
        "departmentOIDs": [],//部门
        "corporationOIDs": [],//公司
        "status": "all"//员工状态
      },//缓存变量
      CREATE_DATA_TYPE: true,
      loading: false,
      showImportPersonModel: false,
      progressImportErrInfo: 1,
      showImportErrInfo: false,
      transactionOID: null,
      isReadOnly: this.props.currentPageRoute.operationType === "R" || false, // "0"为只读，"1"为读写
      errorsList: [
        {
          line: "",
          msg: ""
        },
      ],
      fileList: [],
      flieUploading: false,//文件是否正在上传
      data: [],//条件下所有人
      exportList,
      pagination: {
        page: 0,
        total: 0,
        pageSize: 10,
      },

      params: {
        "keyword": "",
        "departmentOIDs": [],
        "corporationOIDs": [],
        "status": "all"
      },
      extraDep: {
        res: [],
        title: messages('enterprise-manage.key311'/*请选择*/),
        depClassName: "f-right select-dep-close-wrap",
        className: ["f-right select-dep-close-wrap", "f-right select-dep-close-wrap select-dep-close-wrap-show"]
      },
      searchForm: [
        {
          type: 'input',
          id: 'keyword',
          label: messages('enterprise-manage.key365')/*姓名、工号、部门、邮箱、电话*/,
          event: "keywordChange"
        },
        {
          type: 'list',
          id: 'corporationOIDs',
          label: messages('enterprise-manage.key313'/*公司*/),
          listType: 'all_company_with_legal_entity',
          labelKey: 'companyName',
          valueKey: 'companyOID',
          placeholder: messages('enterprise-manage.key311'/*请选择*/),
          event: "companyOIDChange"
        },
        {
          type: 'select',
          id: 'status',
          label: messages('enterprise-manage.key314'/*状态*/),
          event: "statusChange",
          defaultValue: "all",
          options: employeeStatusList
        },

      ],
      columns: [
        {
          title: messages('enterprise-manage.key313'/*公司*/),
          key: "companyName",
          dataIndex: 'companyName',
          render: text => antdc.renderPopover(text)
        },
        {
          title: messages('enterprise-manage.key316'/*工号*/),
          key: "employeeID",
          dataIndex: 'employeeID',
          render: text => antdc.renderPopover(text)
        },
        {
          title: messages('enterprise-manage.key317'/*姓名*/),
          key: "fullName",
          dataIndex: 'fullName',
          render: text => antdc.renderPopover(text)
        },
        {
          title: messages('enterprise-manage.key318'/*部门*/),
          key: "departmentName",
          dataIndex: 'departmentName',
          render: (text, record) => this.renderPopover(text, record)
        },
        {
          title: messages('enterprise-manage.key319'/*联系方式*/),
          key: "mobile",
          dataIndex: 'mobile',
          render: text => antdc.renderPopover(text)
        },
        {
          title: messages('enterprise-manage.key320'/*邮箱*/),
          key: "email",
          dataIndex: 'email',
          render: text => antdc.renderPopover(text)
        },
        {
          title: messages('enterprise-manage.key314'/*状态*/),
          key: "status",
          dataIndex: 'status',
          render: (text) => {
            if (text === 1001) {
              return antdc.renderPopover(messages('enterprise-manage.key17'));
            } else if (text === 1002) {
              return antdc.renderPopover(messages('enterprise-manage.key18'));
            } else if (text === 1003) {
              return antdc.renderPopover(messages('enterprise-manage.key19'));
            }
          }
        },
        {
          title: messages('enterprise-manage.key321'/*操作*/),
          dataIndex: "id",
          key: "id",
          render: (text, record) => (
            <span>
              <a onClick={(e) => this.editItemPerson(e, record)}>{messages("common.detail")}</a>
            </span>)
        }
      ],
    }
    //输入完毕之后再搜
    this.eventSearchAreaHandle = debounce(this.eventSearchAreaHandle, 250);
  }

  componentDidMount() {
    let _pagination = this.getBeforePage();
    let pagination = this.state.pagination;
    pagination.page = _pagination.page;
    pagination.current = _pagination.page + 1;
    this.setState({
      pagination
    }, () => {
      this.clearBeforePage();
      //取出页面缓存状态
      let cache = localStorage.getItem("person-manage-cache");
      let cacheObj = {};
      if (cache + "" !== 'null' && cache + "" !== '{}') {
        //cache要有值
        cacheObj = JSON.parse(cache);
      } else {
        this.getPersonList();
      }
      // 人员导入方式：this.props.company.createDataType如果是 1002，属于接口导入
      // 新增与导入按钮需要隐藏
      let CREATE_DATA_TYPE = (parseInt(this.props.company.createDataType) !== 1002);
      this.setState({
        CREATE_DATA_TYPE,
        cacheObj
      }, () => {
        this.setDefaultSearchForm(this.state.cacheObj);
      })
    })
  }

  renderPopover = (text, record) => {
    return (
      <span>
        {text ? <Popover placement="topLeft" content={record.departmentPath} overlayStyle={{maxWidth: 500}}>{text}</Popover> : '-'}
      </span>
    );
  };

  //设置默认的搜索值
  setDefaultSearchForm = (defaultVal) => {
    if (isEmptyObj(defaultVal)) {
      return
    }
    const {params, searchForm, extraDep} = this.state;
    let deps = [];
    searchForm[0].defaultValue = defaultVal.keyword;
    searchForm[1].defaultValue = defaultVal.corporationOIDs;
    searchForm[2].defaultValue = defaultVal.status || "all";
    //部门的稍微麻烦一点
    extraDep.res = defaultVal.departmentOIDs || [];
    if (extraDep.res.length > 0) {
      extraDep.depClassName = extraDep.className[1];
    } else {
      extraDep.depClassName = extraDep.className[0];
    }
    for (let i = 0; i < extraDep.res.length; i++) {
      deps.push(extraDep.res[i].departmentOID);
    }
    extraDep.title = this.renderButtonTitle(extraDep.res);
    //查询参数，重新设置
    let corporationOIDs = [];
    if (defaultVal && defaultVal.corporationOIDs && defaultVal.corporationOIDs.map) {
      corporationOIDs = defaultVal.corporationOIDs.map((data) => {
        return data.companyOID
      });
    }
    Object.assign(params, {
      keyword: defaultVal.keyword,
      corporationOIDs: corporationOIDs,
      status: defaultVal.status || "all",
      departmentOIDs: deps,
    });
    this.setState({
      extraDep,
      params
    }, () => {
      this.getPersonList();
    })
    //尚未激活的人
    setTimeout(() => {
      this.setState({
        params: deepCopy(params)
      })
    }, 1500)
  };

  //获取员工表格
  getPersonList = () => {
    const {pagination, params} = this.state;
    this.setState({
      loading: true,
    });
    const keyword = params.keyword
    let _params = {
      "sort": "status",
      "page": pagination.page,
      "size": pagination.pageSize,
      "keyword": params.keyword,
      "departmentOID": params.departmentOIDs,
      "corporationOID": params.corporationOIDs,
      "status": params.status,
    };
    PMService.searchPersonInDep(_params)
      .then((response) => {
        pagination.total = Number(response.headers['x-total-count']);
        if (keyword === this.state.params.keyword) {
          this.setState({
            loading: false,
            data: response.data,
            pagination,
          })
        }
      })
  };

  //点击搜搜索
  handleSearch = (values) => {
    const {params, pagination} = this.state;
    Object.assign(params, {
      keyword: values.keyword,
      corporationOIDs: values.corporationOIDs,
      status: values.status,
    });
    pagination.page = 0;
    pagination.current = 1;
    //这个地方用deepCopy，只是因为在子组件要监听nextProps变化
    this.setState({
      pagination,
      params: deepCopy(params)
    }, () => {
      this.getPersonList()
    })
  };
  /*
  * 员工信息，工号，电话等关键字是及时搜索
  * 要缓存选择状态
  * */
  eventSearchAreaHandle = (e, item) => {
    //翻页的时候，缓存数据
    let {cacheObj, pagination, params} = this.state;
    if (e === "keywordChange") {
      pagination.page = 0;
      pagination.current = 1;
      cacheObj.keyword = item;
      params.keyword = item;
      //这个地方用deepCopy，只是因为在子组件要监听nextProps变化
      this.setState({
        pagination,
        cacheObj,
        params: deepCopy(params)
      }, () => {
        this.getPersonList()
      })
    }
    if (e === "companyOIDChange") {
      cacheObj.corporationOIDs = deepCopy(item);
      let corporationOIDs = item.map((data) => data.companyOID);
      params.corporationOIDs = corporationOIDs;
      this.state.cacheObj = cacheObj;
      this.state.pagination = pagination;
      this.state.params = deepCopy(params);
    }
    if (e === "statusChange") {
      params.status = item;
      cacheObj.status = item;
      this.state.pagination = pagination;
      this.state.cacheObj = cacheObj;
      this.state.params = deepCopy(params);
    }
  };

  clearSearchHandle = () => {
    localStorage.setItem("person-manage-cache", null);
    const {searchForm, params, pagination, cacheObj} = this.state;
    searchForm[0].defaultValue = "";
    searchForm[1].defaultValue = [];
    searchForm[2].defaultValue = "all";
    //部门重置有下面的this.selectDepSearchArea([]);
    Object.assign(pagination, {
      page: 0,
      current: 1,
      total: 0,
      pageSize: 10
    });
    let resSetParams = {
      keyword: "",
      departmentOIDs: [],
      corporationOIDs: [],
      status: 'all',
    };
    Object.assign(params, resSetParams);
    Object.assign(cacheObj, resSetParams);
    this.setState({
      params,
      pagination,
      cacheObj,
      searchForm
    }, () => {
      this.handleSearch(this.state.params);
    });
    this.selectDepSearchArea([]);
  };

  //新增员工
  handleCreatePerson = () => {
    this.setBeforePage(this.state.pagination);
    let cacheObj = this.state.cacheObj;
    let cacheObjStr = JSON.stringify(cacheObj);
    localStorage.setItem("person-manage-cache", cacheObjStr);
    let path = menuRoute.getRouteItem('person-detail', 'key').url.replace(":userOID", "NEW");
    this.context.router.push(path);
  };

  //编辑员工
  editItemPerson = (e, record) => {
    this.setBeforePage(this.state.pagination);
    let {cacheObj} = this.state;
    let cacheObjStr = JSON.stringify(cacheObj);
    localStorage.setItem("person-manage-cache", cacheObjStr);
    let path = menuRoute.getRouteItem('person-detail', 'key').url.replace(":userOID", record.userOID);
    this.context.router.push(path);
  };

  //分页点击
  onChangePager = (pagination, filters, sorter) => {
    this.setState({
      pagination: {
        current: pagination.current,
        page: pagination.current - 1,
        pageSize: pagination.pageSize
      }
    }, () => {
      this.getPersonList();
    })
  };

  onMouseLeaveDepTag = (e) => {
    e.stopPropagation();
  };
  onMouseEnterDepTag = (e) => {
    e.stopPropagation();
  };
  //清除已经选择的部门
  onCloseDepTag = (e) => {
    e.stopPropagation();
    this.selectDepSearchArea([]);
  };

  //渲染已经选择的部门
  renderButtonTitle(titleArr) {
    if (titleArr.length < 1) {
      return messages('enterprise-manage.key311'/*请选择*/);
    }
    let node = [];
    titleArr.map((item, i) => {
      node.push(<Tag key={i}>{item.name}</Tag>);
    });
    return node;
  }

  //选择了部门的回调
  selectDepSearchArea = (res) => {
    //翻页的时候，缓存数据
    let {cacheObj, params, extraDep} = this.state;
    cacheObj.departmentOIDs = deepCopy(res);
    let deps = [];
    extraDep.res = res;
    if (extraDep.res.length > 0) {
      extraDep.depClassName = extraDep.className[1];
    } else {
      extraDep.depClassName = extraDep.className[0];
    }
    for (let i = 0; i < extraDep.res.length; i++) {
      deps.push(extraDep.res[i].departmentOID);
    }
    params.departmentOIDs = deps;
    extraDep.title = this.renderButtonTitle(extraDep.res);
    this.setState({
      extraDep,
      params
    })
  };

  //渲染导出的列表
  renderExportList = (list) => {
    let {params} = this.state;
    let exportCondition = Object.assign({}, params, {"sort": "status"});
    return list.map((data) => {
      return <Menu.Item key={data.type}>
        <ExportModal
          codeCheck={true}
          exportTitle={data.name}
          exportType="USER"
          exportCondition={exportCondition}
          exportCommand={data.command}
        />
      </Menu.Item>
    })
  };
  gotoExtend = ()=>{
    this.context.router.push(menuRoute.getMenuItemByAttr('extend-field', 'key').children.extendField.url);
  }

  //人员导入的错误信息-end
  render() {
    let {extraDep, loading, searchForm, pagination, CREATE_DATA_TYPE, params, columns, data, isReadOnly} = this.state;
    let exportCondition = Object.assign({}, params, {"sort": "status"});
    let {tenantMode} = this.props;
    const menu = (
      <Menu>{this.renderExportList(this.state.exportList)}</Menu>
    );
    const templates = [
      {
        downloadName: messages('enterprise-manage.key307'/*人员信息导入模板*/),
        templateName: messages('enterprise-manage.key322'/*人员信息模板*/),
        downloadUrl: "/api/users/v2/fullInfo/template/export",
        downloading: "peopleLoading"
      },
      {
        downloadName: messages('enterprise-manage.key308'/*银行信息导入模板*/),
        templateName: messages('enterprise-manage.key324'/*银行信息模板*/),
        downloadUrl: "/api/contact/bank/accounts/template/export",
        downloading: "bankLoading"
      },
      {
        downloadName: messages('enterprise-manage.key309'/*证件信息导入模板*/),
        templateName: messages('enterprise-manage.key325'/*证件信息模板*/),
        downloadUrl: "/api/contact/cards/template/export",
        downloading: "certificateLoading"
      },
      {
        downloadName: messages('enterprise-manage.key379')/*员工岗位信息导入模板*/,
        templateName: messages('enterprise-manage.key380')/*员工岗位信息模板*/,
        downloadUrl: "/api/user/jobs/template/download",
        downloading: "positionLoading"
      },
      {
        downloadName: messages('enterprise-manage.key395')/*消费商信息导入模板*/,
        templateName: messages('enterprise-manage.key396')/*消费商模板*/,
        downloadUrl: "/api/contact/supplier/ctrip/template/export",
        downloading: "supplierLoading"
      },
    ];
    const downLinks = (
      <a className="download-list-item-a"
         href="http://helioscloud-uat-static.oss-cn-shanghai.aliyuncs.com/bank_info.xlsx">
        {messages('enterprise-manage.key37'/*银行基础数据（录入银行信息时请根据银行数据录入，该文件无须上传）*/)}
      </a>
    );
    return (
      <div className="person-manage-wrap">
        <SearchArea
          extraFields={
            [
              <div>
                <div className="select-dep-search-area-title">
                  {messages('enterprise-manage.key318'/*部门*/) + ":"}
                </div>
                <div className="select-dep-search-area">
                  <div className="f-left select-dep-wrap">
                    <SelectDepOrPerson
                      renderButton={false}
                      title={extraDep.title}
                      onlyDep={true}
                      onConfirm={this.selectDepSearchArea}/>
                  </div>
                  <div className={extraDep.depClassName}
                       onMouseLeave={this.onMouseLeaveDepTag}
                       onMouseEnter={this.onMouseEnterDepTag}
                       onClick={this.onCloseDepTag}>
                    <Icon type="close-circle" className="closeCircle"/>
                  </div>
                </div>
              </div>
            ]
          }
          clearLoading={loading}
          loading={loading}
          eventHandle={this.eventSearchAreaHandle}
          searchForm={searchForm}
          clearHandle={this.clearSearchHandle}
          submitHandle={this.handleSearch}/>
        <div className="table-header">
          <div
            className="table-header-title">
            {messages('common.total',
              {total: `${pagination.total}`})}
          </div>
          {/*共搜索到*条数据*/}
          <div className="table-header-buttons">
            <div className="f-left">
              {CREATE_DATA_TYPE ? <Button type="primary"
                                          disabled={isReadOnly}
                                          onClick={this.handleCreatePerson}>
                {messages('enterprise-manage.key327'/*新增员工*/)}
              </Button> : <span/>}
              {CREATE_DATA_TYPE ?
                <ImportModal buttonName={messages('enterprise-manage.key328'/*导入人员数据*/)}
                             leftContent={messages('enterprise-manage.key397')/*主信息模板（必须导入）,包含个人基本信息、默认一套银行&证件信息、消费商信息补充信息模板（上传前必须先导入主数据）&证件信息*/}
                             downLinks={downLinks}
                             templates={templates}
                             hasErrInfo={true}
                             buttonDisabled={isReadOnly}
                             uploadUrl={`${config.baseUrl}/api/refactor/users/v2/info/import`}
                             showErrUrl={`${config.baseUrl}` + "/api/batch/transaction/logs/v2/${transactionOID}"}
                             exportErrUrl={`${config.baseUrl}` + "/api/batch/transaction/logs/failed/export/${transactionOID}"}
                             onCancel={this.getPersonList}/>
                : null
              }
              &nbsp;&nbsp;&nbsp;
              <div className="drop-down-export-modal-wrap">
                <ExportModal
                  codeCheck={true}
                  exportTitle={messages('enterprise-manage.key329'/*导出人员数据*/)}
                  exportType="USER"
                  exportCondition={exportCondition}
                  exportCommand={"user_full_info"}
                />
                <Dropdown overlay={menu}
                          disabled={loading}>
                  <a className="ant-dropdown-link" href="#">
                    <Icon type="down"/>
                  </a>
                </Dropdown>
              </div>
            </div>
            <div className="f-left">
              <Button type="primary"
                      disabled={!tenantMode || isReadOnly}
                      onClick={this.gotoExtend}>
                {messages('enterprise-manage.key406')/*员工扩展字段*/}
              </Button>
            </div>
            <div className="f-left">
              <InvitePersonModal params={params}/>
            </div>
            <div className="clear"/>
          </div>
        </div>
        <ResizeTable
          loading={loading}
          dataSource={data}
          columns={columns}
          pagination={pagination}
          size="middle"
          rowKey={'id'}
          bordered={true}
          onChange={this.onChangePager}
        />
      </div>
    )
  }
}

PersonManage.propTypes = {};

PersonManage.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    user: state.login.user,
    tenantMode: state.main.tenantMode,
    company: state.login.company,
    currentPageRoute: state.main.currentPageRoute
  }
}

export default connect(mapStateToProps)(PersonManage);

